package com.troila.xfspark.websocket;


import com.troila.xfspark.model.SparkProperties;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

public class SparkWrapper {

    private SparkWrapper() {
    }

    private static SparkWrapper single = null;

    public static SparkWrapper getInstance() {
        if (single == null) {
            single = new SparkWrapper();
        }
        return single;
    }

    public String websocketUrl(SparkProperties properties) throws Exception {
        String authUrl = getAuthUrl(properties.getApiUrl(), properties.getApiKey(), properties.getApiSecret());
        return authUrl.replace("http://", "ws://").replace("https://", "wss://");
    }

    private String getAuthUrl(String hostUrl, String apiKey, String apiSecret) throws Exception {
        URL url = new URL(hostUrl);
        // 时间
        SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
        format.setTimeZone(TimeZone.getTimeZone("GMT"));
        String date = format.format(new Date());
        // 拼接
        String preStr = "host: " + url.getHost() + "\n" +
                "date: " + date + "\n" +
                "GET " + url.getPath() + " HTTP/1.1";
        // SHA256加密
        SecretKeySpec spec = new SecretKeySpec(apiSecret.getBytes(StandardCharsets.UTF_8), "hmacsha256");
        Mac mac = Mac.getInstance("hmacsha256");
        mac.init(spec);

        byte[] hexDigits = mac.doFinal(preStr.getBytes(StandardCharsets.UTF_8));
        // Base64加密
        String sha = Base64.getEncoder().encodeToString(hexDigits);
        // 拼接
        String authorization = String.format("api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"", apiKey, "hmac-sha256", "host date request-line", sha);
        // 拼接地址
        StringBuilder builder = new StringBuilder();
        builder.append("https://" + url.getHost() + url.getPath() + "?");
        builder.append("authorization=" + Base64.getEncoder().encodeToString(authorization.getBytes(StandardCharsets.UTF_8)));
        builder.append("&date=" + date);
        builder.append("&host=" + url.getHost());
        return builder.toString();
    }

}
